package cn.hml.user.service.impl;

import cn.hml.basic.constant.WxConstants;
import cn.hml.basic.dto.LoginDto;
import cn.hml.basic.exception.BusinessException;
import cn.hml.basic.util.AjaxResult;
import cn.hml.basic.util.HttpUtil;
import cn.hml.basic.util.Md5Utils;
import cn.hml.basic.util.StrUtils;
import cn.hml.user.domain.Logininfo;
import cn.hml.user.domain.User;
import cn.hml.user.domain.Wxuser;
import cn.hml.user.mapper.LogininfoMapper;
import cn.hml.user.mapper.UserMapper;
import cn.hml.user.mapper.WxuserMapper;
import cn.hml.user.service.ILogininfoService;
import cn.hml.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WxuserMapper wxuserMapper;


    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //一：校验 - 空值校验
        if(StringUtils.isEmpty(loginDto.getAccount())||StringUtils.isEmpty(loginDto.getCheckPass())){
            throw new BusinessException("信息不能为空");
        }
        //二：校验 - 校验账号【username + type】
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if(logininfo == null){
            throw new BusinessException("账号或密码错误");
        }
        //三：校验 - 校验密码【密码要加密加盐】
        String inputMd5pwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        if(!inputMd5pwd.equals(logininfo.getPassword())){
            throw new BusinessException("账号或密码错误");
        }
        //四：校验 - 用户是否被禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("该账号被禁用，请联系管理员");
        }
        //五：使用uuid生成token，将token作为key把登录信息对象保存到redis，30分钟有效
        String token = UUID.randomUUID().toString();//随机36位的字符串
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        //六：将token和登录信息对象保存到Map进行返回
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("logininfo",logininfo);

        return map;
    }


    @Override
    public AjaxResult wechatLogin(String code) {
        //一：组装第二个请求地址
        String url =   WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET).replace("CODE",code);

        //二：使用HttpUtil工具类发送请求,返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);

        //三：将json格式的字符串转成json对象，并获取里面的token和openid
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObj.getString("access_token");
        String openid = jsonObj.getString("openid");
        //四：根据openid去查t_wxuser表
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);
        //如果通过openid查询到了wxuser对象
        if(wxuser!=null){//绑定过
            User user = userMapper.loadById(wxuser.getUserId());
            if(user != null){//并且绑定了user对象
                //免密登录
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                String token = UUID.randomUUID().toString();//随机36位的字符串
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

                //将token和登录信息对象保存到Map进行返回
                Map<String,Object> map = new HashMap<>();
                map.put("token",token);
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                map.put("logininfo",logininfo);
                return AjaxResult.me().setResultObj(map);
            }
        }
         String params = "?accessToken="+accessToken+"&openid="+openid;
        System.out.println("======================");
        System.out.println(accessToken);
        System.out.println(openid);
        System.out.println("======================");
        return AjaxResult.me().setResultObj(params).setSuccess(false);
    }
    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openid = map.get("openid");
        //1.校验 - 空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空");
        }
        //2.校验 - 手机验证码校验：是否过期，是否正确 【binder:18566565555 - 9527:1555566666666】
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj == null){
            throw new BusinessException("手机验证码过期");
        }
        if(!obj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("手机验证码错误");
        }
        //3.组装第三个请求地址
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
        //4.通过token和openid发送第三个请求，返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson将json格式的字符串转成json对象，再转成一个Wxuser对象【没有user_id】
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //6.先通过openid去找t_wxuser ,如果有直接删除
        Wxuser dbWxuser = wxuserMapper.loadByOpenid(openid);
        if(dbWxuser!=null){
            wxuserMapper.del(dbWxuser.getId());
        }
        //7.想办法创建一个User对象 - 通过phone去创建一个User对象，密码是多少？-随机
        User user = userMapper.loadByPhone(phone); //以前是通过手机号码注册，现在又想通过微信绑定登录
        if(user==null){
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);

            logininfoMapper.sava(logininfo);
            user.setLogininfoId(logininfo.getId());
            //8.添加User对象 => 生成一个自增id => 将User_id设置到WxUser对象
            userMapper.sava(user);
        }

        //9.添加WxUser对象到数据库
        wxuser.setUserId(user.getId());
        wxuserMapper.sava(wxuser);

        //10.做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        String token = UUID.randomUUID().toString();//随机36位的字符串
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        //将token和登录信息对象保存到Map进行返回
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        resultMap.put("logininfo",logininfo);
        return AjaxResult.me().setResultObj(resultMap);
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        /*
        "openid":"OPENID",
        "nickname":"NICKNAME",
        "sex":1,
        "province":"PROVINCE",
        "city":"CITY",
        "country":"COUNTRY",
        "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
        "privilege":[
        "PRIVILEGE1",
        "PRIVILEGE2"
        ],
        "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
        * */
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObj.getString("openid"));
        wxuser.setNickname(jsonObj.getString("nickname"));
        wxuser.setHeadimgurl(jsonObj.getString("headimgurl"));
        wxuser.setUnionid(jsonObj.getString("unionid"));
        return wxuser;
    }
}




